﻿#region Copyright
/* Product of DTL Software
 * Product Name : Support Memmory
 * Author : dinhtienlam.spkt@gmail.com
 * About: Developer of DTL Software
 * Contact : 0966 330 237
 */
#endregion

#region Using default
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Linq.Expressions; 
#endregion

namespace Lamdt.Linq
{
    public static class DynamicLinq
    {
        public static IQueryable<T> Where<T>(this IQueryable<T> query, string columnName, object value, WhereOperation operation)
        {
            if (string.IsNullOrEmpty(columnName))
                return query;
            ParameterExpression parameter = Expression.Parameter(query.ElementType, "p");
            MemberExpression memberAccess =  MemberExpression.Property((parameter as Expression), columnName);
            ConstantExpression filter = Expression.Constant
                (
                    Convert.ChangeType(value, memberAccess.Type)
                );

            //switch operation
            Expression condition = null;
            LambdaExpression lambda = null;
            switch (operation)
            {
                //equal ==
                case WhereOperation.Equal:
                    condition = Expression.Equal(memberAccess, filter);
                    lambda = Expression.Lambda(condition, parameter);
                    break;
                //not equal !=
                case WhereOperation.NotEqual:
                    condition = Expression.NotEqual(memberAccess, filter);
                    lambda = Expression.Lambda(condition, parameter);
                    break;
                //string.Contains()
                case WhereOperation.Contains:
                    condition = Expression.Call(memberAccess,
                        typeof(string).GetMethod("Contains"),
                        Expression.Constant(value));
                    lambda = Expression.Lambda(condition, parameter);
                    break;
            }


            MethodCallExpression result = Expression.Call(
                   typeof(Queryable), "Where",
                   new[] { query.ElementType },
                   query.Expression,
                   lambda);

            return query.Provider.CreateQuery<T>(result);
        }

        /// <summary>
        /// Order by column name
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <param name="columnName"> Column name is ordered</param>
        /// <param name="isASC"> true if order by ascending, other whise false</param>
        /// <returns></returns>
        public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string columnName, bool isASC = true)
        {
            if (string.IsNullOrEmpty(columnName))
                throw new ArgumentException(columnName);
            PropertyInfo property = source.ElementType.GetProperty(columnName);
            if (property == null) 
                throw new ArgumentException(columnName);
            ParameterExpression parameter = Expression.Parameter(source.ElementType, "p");
            MemberExpression memberAccess = MemberExpression.Property(parameter, columnName);
            LambdaExpression orderByExpression = Expression.Lambda(memberAccess, parameter);
            MethodCallExpression resultExpression =
                Expression.Call
                (
                    typeof(Queryable),
                    isASC ? "OrderBy" : "OrderByDescending",
                    new Type[] { source.ElementType, property.PropertyType },
                    source.Expression,
                    Expression.Quote(orderByExpression)
                );
            return source.Provider.CreateQuery<T>(resultExpression);
        }

        public static IQueryable<T> ThenOrderBy<T>(this IQueryable<T> source, string columnName, bool isASC = true)
        {
            if (string.IsNullOrEmpty(columnName))
                throw new ArgumentException(columnName);
            PropertyInfo property = source.ElementType.GetProperty(columnName);
            if (property == null)
                throw new ArgumentException(columnName);
            ParameterExpression parameter = Expression.Parameter(source.ElementType, "p");
            MemberExpression memberAccess = MemberExpression.Property(parameter, columnName);
            LambdaExpression orderByExpression = Expression.Lambda(memberAccess, parameter);
            MethodCallExpression resultExpression =
                Expression.Call
                (
                    typeof(Queryable),
                    isASC ? "ThenBy" : "ThenByDescending",
                    new Type[] { source.ElementType, property.PropertyType },
                    source.Expression,
                    Expression.Quote(orderByExpression)
                );
            return source.Provider.CreateQuery<T>(resultExpression);
        } 
    }

    public enum WhereOperation
    {
        NotEqual,
        Equal,
        Contains
    }
}
